/**
 * 
 */
package persistence.demoproxy;


import java.lang.reflect.Method;

import javassist.util.proxy.MethodFilter;
import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.ProxyFactory;
import javassist.util.proxy.ProxyObject;

/**
 * Demo javaassist
 * Intercepter l'appel à la méthode getTitle d'un Book
 * @author dga
 * 
 */
public class TestJavassist {
   private Class proxyClazz;
  /**
   * @param args
   * @throws IllegalAccessException 
   * @throws InstantiationException 
   */
  private boolean toFilter(String name){
    return name.equals("getTitle");
  }

  public void createProxy() throws InstantiationException, IllegalAccessException {
    ProxyFactory f = new ProxyFactory();
    f.setSuperclass(Book.class);
    f.setFilter(new MethodFilter() {
      public boolean isHandled(Method m) {
        System.out.println("Calling filter " + m.getName());
        if (TestJavassist.this.toFilter(m.getName()))   // La classe interne a accès à l'externe
          return true;
        return false;
      }
    });
    proxyClazz = f.createClass();
  }
  
  public Object createInstance() throws InstantiationException, IllegalAccessException{
    Object created = proxyClazz.newInstance();
    ((ProxyObject) created).setHandler(new PersistentClassHandler());
    return created;
  }

  public static void main(String[] args) throws Exception {
    TestJavassist tja = new TestJavassist();
    tja.createProxy();
    Book b = (Book)(tja.createInstance());
    b.setTitle("Java");
    System.out.println(b.getTitle());
  }

}
